package com.wonders.demo.module.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wonders.demo.module.po.UserPo;
import com.wonders.demo.module.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author wonders
 */
@Controller
@RequestMapping("/sys/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/list")
    public String list(Model model) {
        List<UserPo> list = userService.list();
        model.addAttribute("userList", list);
        return "user";
    }

    @RequestMapping("/view")
    @ResponseBody
    public UserPo view(String id) {
        List<UserPo> list = userService.list(new QueryWrapper<UserPo>().eq("id", id));
        Optional<UserPo> first = list.stream().findFirst();
        if (first.isPresent()) {
            return first.get();
        } else {
            return null;
        }
    }

    /**
     * 编程式
     *
     * @param userPo
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public boolean update(UserPo userPo) {
        boolean b = false;
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("sys:user:update")) {
            b = userService.updateById(userPo);
        }
        return b;
    }

    /**
     * 注解式
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions("sys:user:delete")
    public boolean delete(String id) {
        boolean b = userService.removeById(id);
        return b;
    }

}
